#!/usr/bin/env bash

# Test basic GitHub backend functionality with real tools
cat <<EOF >mise.toml
[tools]
"github:jdx/mise-test-fixtures" = { version = "1.0.0", asset_pattern = "hello-world-1.0.0.tar.gz", bin_path = "hello-world-1.0.0/bin", postinstall = "chmod +x \$MISE_TOOL_INSTALL_PATH/hello-world-1.0.0/bin/hello-world" }
EOF

mise install
assert_contains "mise x -- hello-world" "hello world"

# Test GitHub backend with platform-specific URLs
cat <<EOF >mise.toml
[tools."github:jdx/mise-test-fixtures"]
platform_darwin_arm64_url = "https://mise.jdx.dev/test-fixtures/hello-world-1.0.0.tar.gz"
platform_darwin_amd64_url = "https://mise.jdx.dev/test-fixtures/hello-world-1.0.0.tar.gz"
platform_linux_amd64_url = "https://mise.jdx.dev/test-fixtures/hello-world-1.0.0.tar.gz"
version = "1.0.0"
bin_path = "hello-world-1.0.0/bin"
postinstall = "chmod +x \$MISE_TOOL_INSTALL_PATH/hello-world-1.0.0/bin/hello-world"
strip_components = 1
EOF

mise install
assert_contains "mise x -- hello-world" "hello world"

# Test GitHub backend with a raw file asset
cat <<EOF >mise.toml
[tools]
"github:jdx/mise-test-fixtures" = { version = "1.0.0", asset_pattern = "hello-world", postinstall = "chmod +x \$MISE_TOOL_INSTALL_PATH/hello-world" }
EOF

mise install
assert_contains "mise x -- hello-world" "hello world"

# Test GitHub backend with mise.lock checksum generation
export MISE_LOCKFILE=1
export MISE_EXPERIMENTAL=1

touch mise.lock
cat <<EOF >mise.toml
[tools]
"github:jdx/mise-test-fixtures" = { version = "1.0.0", asset_pattern = "hello-world-1.0.0.tar.gz", bin_path = "hello-world-1.0.0/bin", postinstall = "chmod +x \$MISE_TOOL_INSTALL_PATH/hello-world-1.0.0/bin/hello-world" }
EOF

mise uninstall github:jdx/mise-test-fixtures
assert "mise install"
# Verify mise.lock is written correctly with checksums
assert_contains "cat mise.lock" '[tools."github:jdx/mise-test-fixtures"]'
assert_contains "cat mise.lock" 'version = "1.0.0"'
assert_contains "cat mise.lock" 'backend = "github:jdx/mise-test-fixtures"'
# Get the current platform key
PLATFORM_KEY=$(mise x --cd . -- bash -c "echo \"\$(uname -s | tr '[:upper:]' '[:lower:]' | sed 's/darwin/macos/')-\$(uname -m | sed 's/x86_64/x64/' | sed 's/aarch64/arm64/')\"")
assert_contains "cat mise.lock" "[tools.\"github:jdx/mise-test-fixtures\".platforms.$PLATFORM_KEY]"
# GitHub API provides sha256 digests for release assets
# This checksum is the same across all platforms (macos-arm64, linux-x64, linux-arm64)
# because hello-world-1.0.0.tar.gz is a generic tarball, not platform-specific
assert_contains "cat mise.lock" 'checksum = "sha256:dbca4f08377d70dc0828f5822fc47ecec3895cd9a6dacbc54cc984d346a571af"'
assert_contains "cat mise.lock" 'url = "https://github.com/jdx/mise-test-fixtures/releases/download/v1.0.0/hello-world-1.0.0.tar.gz"'
assert_contains "cat mise.lock" 'url_api = "https://api.github.com/repos/jdx/mise-test-fixtures/releases/assets/272317030"'
assert_contains "cat mise.lock" 'size = '
